package com.example.myapplication.util;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.myapplication.bean.People;

import java.util.ArrayList;
import java.util.List;

public class DBAdapter {
    private static final String DB_NAME = "people.db";
    private static final String DB_TABLE = "peopleinfo";
    private static final int DB_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_AGE = "age";
    public static final String KEY_HEIGHT = "height";
    private SQLiteDatabase db;
    private Context context;
    private DBOpenHelper dbOpenHelper;

    public DBAdapter(Context context) {
        this.context = context;
    }

    private static class DBOpenHelper extends SQLiteOpenHelper {
        public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        private static final String DB_CREATE = "create table " +
                DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " +
                KEY_NAME + " text not null, " + KEY_AGE + " integer," + KEY_HEIGHT + " float);";

        //onCreate()函数在数据库第一次建立时被调用，一般用来创建数据库中的表，并完成初始化工作
        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL(DB_CREATE);
        }

        //onUpgrade()函数在数据库需要升级时被调用，一般用来删除旧的数据库表，并将数据转移到新版本的数据库表中
        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(sqLiteDatabase);
        }
    }

    public void open() {
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        try {
            db = dbOpenHelper.getWritableDatabase();
        } catch (Exception e) {
            db = dbOpenHelper.getReadableDatabase();
        }
    }

    public void close() {
        if (db != null) {
            db.close();
        }
    }

    /*
    操作
     */
    public long insert(People people) {
        ContentValues content = new ContentValues();
        content.put(KEY_NAME, people.getName());
        content.put(KEY_AGE, people.getAge());
        content.put(KEY_HEIGHT, people.getHeight());
        return db.insert(DB_TABLE, null, content);
    }

    public long deleteAllData() {
        return db.delete(DB_TABLE, null, null);
    }

    public long deleteById(long id){
        return db.delete(DB_TABLE, KEY_ID + "=" + id, null);
    }

    public long updateById(People people){
        ContentValues updateContent = new ContentValues();
        updateContent.put(KEY_NAME, people.getName());
        updateContent.put(KEY_AGE, people.getAge());
        updateContent.put(KEY_HEIGHT, people.getHeight());
        return db.update(DB_TABLE, updateContent, KEY_ID +"=" + people.getId(), null);
    }

    @SuppressLint("Range")
    public List<People> convertToPeopleList(Cursor cursor){
        int count = cursor.getCount();
        if(count == 0 || !cursor.moveToFirst()) return null;
        List<People> peopleList = new ArrayList<>();
        for(int i = 0; i < count; i++){
            People people = new People();
            people.setId(cursor.getInt(0));
            people.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
            people.setAge(cursor.getInt(cursor.getColumnIndex(KEY_AGE)));
            people.setHeight(cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT)));
            peopleList.add(people);
            cursor.moveToNext();
        }
        return peopleList;
    }
    @SuppressLint("Range")
    public People convertToPeople(Cursor cursor){
        if(cursor == null || cursor.getCount() == 0 || !cursor.moveToFirst()) return null;
        People people = new People();
        people.setId(cursor.getInt(0));
        people.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
        people.setAge(cursor.getInt(cursor.getColumnIndex(KEY_AGE)));
        people.setHeight(cursor.getFloat(cursor.getColumnIndex(KEY_HEIGHT)));
        return people;
    }

    public People getById(long id){
        Cursor cursor = db.query(DB_TABLE, new String[]{KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT}, KEY_ID + "=" + id, null, null, null, null);
        return convertToPeople(cursor);
    }

    public List<People> getAll(){
        Cursor cursor = db.query(DB_TABLE, new String[]{KEY_ID, KEY_NAME, KEY_AGE, KEY_HEIGHT}, null, null, null, null, null);
        return convertToPeopleList(cursor);
    }
}
